package hadlers

import (
	"car-trade-pro/cache"
	"car-trade-pro/modle"
	"car-trade-pro/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}

	var user modle.User

	err := modle.DB.Where("username", username).Debug().Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rab.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误超过3次触发账户临时封禁机制",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rab.Incr(cache.Ctx, redis_key)
		if errCount == 2 {

			cache.Rab.Set(cache.Ctx, redis_key, 3, time.Hour*2)

			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误超过3次需要限制登录2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return
}

func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	var data = modle.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	err := modle.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return

}

func UserRoleList(c *gin.Context) {

	/*
		SELECT *
		FROM
		roles
		LEFT JOIN user_roles on user_roles.rid=roles.id
		WHERE user_roles.uid=1
	*/

	uid, _ := strconv.Atoi(c.Query("uid"))

	var roles []modle.Role
	modle.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid =?", uid).
		Debug().
		Find(&roles)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roles,
	})
	return

}

func RoleNodeList(c *gin.Context) {

	rid, _ := strconv.Atoi(c.Query("rid"))

	/*
		SELECT * FROM
		 nodes
		 LEFT JOIN role_nodes on nodes.id=role_nodes.nid
		 WHERE role_nodes.rid=2
	*/

	var nodes []modle.Node

	modle.DB.Table(" nodes").
		Joins(" LEFT JOIN role_nodes on nodes.id=role_nodes.nid").
		Where("role_nodes.rid =?", rid).
		Debug().
		Find(&nodes)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
	return

}
